package org.jeecg.modules.demo.homepage.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.util.TokenUtils;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.demo.basejobserveitem.entity.BaseJobServeItem;
import org.jeecg.modules.demo.basejobserveitem.service.IBaseJobServeItemService;
import org.jeecg.modules.demo.basemembervipcoupon.service.IBaseMemberVipCouponService;
import org.jeecg.modules.demo.baseorde.entity.BaseOrder;
import org.jeecg.modules.demo.baseorde.service.IBaseOrderService;
import org.jeecg.modules.demo.baseordercommodity.service.IBaseOrderCommodityService;
import org.jeecg.modules.demo.baseordercommoditywriteoff.service.IBaseOrderCommodityWriteoffService;
import org.jeecg.modules.demo.baseorderproject.entity.BaseOrderProject;
import org.jeecg.modules.demo.baseorderproject.service.IBaseOrderProjectService;
import org.jeecg.modules.demo.baseorderservicewriteoff.entity.BaseOrderServiceWriteoff;
import org.jeecg.modules.demo.baseorderservicewriteoff.service.IBaseOrderServiceWriteoffService;
import org.jeecg.modules.demo.baseorderwriteoffrecord.entity.BaseOrderWriteoffRecord;
import org.jeecg.modules.demo.baseorderwriteoffrecord.service.IBaseOrderWriteoffRecordService;
import org.jeecg.modules.demo.basepayorder.service.IBasePayOrderService;
import org.jeecg.modules.demo.basepreorder.service.IBasePreOrderService;
import org.jeecg.modules.demo.commoditygroup.service.ICommodityGroupService;
import org.jeecg.modules.demo.commoditymanagement.entity.CommodityManagement;
import org.jeecg.modules.demo.commoditymanagement.service.ICommodityManagementService;
import org.jeecg.modules.demo.homepage.service.HomePageService;
import org.jeecg.modules.demo.levelset.service.ILevelSetService;
import org.jeecg.modules.demo.membermanagement.entity.MemberManagement;
import org.jeecg.modules.demo.membermanagement.service.IMemberManagementService;
import org.jeecg.modules.demo.projectgroup.service.IProjectGroupService;
import org.jeecg.modules.demo.projectmanagement.service.IProjectManagementService;
import org.jeecg.modules.demo.staffmanagement.service.IStaffManagementService;
import org.jeecg.modules.demo.stockmanage.entity.StockManage;
import org.jeecg.modules.demo.stockmanage.service.IStockManageService;
import org.jeecg.modules.demo.storeinfo.service.IStoreInfoService;
import org.jeecg.modules.demo.viporderrecord.entity.VipOrderRecord;
import org.jeecg.modules.demo.viporderrecord.service.IVipOrderRecordService;
import org.jeecg.modules.util.HashMapEx;
import org.jeecg.modules.util.RedisUtils;
import org.jeecg.modules.util.ToolsUtils;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 首页、数据
 */
@RestController
@RequestMapping("/homePage")
@Slf4j
public class HomePageController {

    @Autowired
    private RedisUtils redisUtils;
    @Autowired
    private HomePageService homePageService;
    @Autowired
    private IMemberManagementService memberManagementService;
    @Autowired
    private IStockManageService stockManageService;
    @Autowired
    private IStaffManagementService staffManagementService;
    @Autowired
    private ICommodityGroupService commodityGroupService;
    @Autowired
    private ICommodityManagementService commodityManagementService;
    @Autowired
    private IProjectGroupService projectGroupService;
    @Autowired
    private IProjectManagementService projectManagementService;
    @Autowired
    private IBaseOrderService baseOrderService;
    @Autowired
    private IBaseOrderCommodityService baseOrderCommodityService;
    @Autowired
    private IBaseOrderProjectService baseOrderProjectService;
    @Autowired
    private IBaseOrderServiceWriteoffService baseOrderServiceWriteoffService;
    @Autowired
    private IBaseOrderCommodityWriteoffService baseOrderCommodityWriteoffService;
    @Autowired
    private IBasePreOrderService basePreOrderService;
    @Autowired
    private IStoreInfoService storeInfoService;
    @Autowired
    private ILevelSetService levelSetService;
    @Autowired
    private IBaseMemberVipCouponService baseMemberVipCouponService;
    @Autowired
    private IBaseOrderWriteoffRecordService baseOrderWriteoffRecordService;
    @Autowired
    private IBasePayOrderService basePayOrderService;
    @Autowired
    private IBaseJobServeItemService baseJobServeItemService;
    @Autowired
    private IVipOrderRecordService vipOrderRecordService;

    @NotNull
    private static Double getMapValueSum(List<Map<String, Object>> banlanceList) {
        Double result = 0D;
        for (Map<String, Object> map : banlanceList) {
            for (Object o : map.values()) {
                if (o instanceof Double) {
                    Double v = (Double) o;
                    result = result + v;
                }
            }
        }
        return result;
    }

    /**
     * 首页-本月数据
     */
    @PostMapping("/data1")
    public Result<?> data1(HttpServletRequest req) {

        String token = TokenUtils.getTokenByRequest(req);
        String storeId = (String) redisUtils.get(RedisUtils.storeId + token);
        if (oConvertUtils.isEmpty(storeId)) {
            return Result.error("请先到首页选择店铺");
        }
        if (storeId.contains("过期")) {
            return Result.error("店铺已过期，续费后才可操作");
        }

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String format = sdf.format(new Date());
        String[] split = format.split("-");
        int year = Integer.parseInt(split[0]);
        int month = Integer.parseInt(split[1]);
        int day = Integer.parseInt(split[2]);
        Calendar c = Calendar.getInstance();
        c.set(Calendar.YEAR, year);
        c.set(Calendar.MONTH, month - 1);
        c.set(Calendar.DAY_OF_MONTH, 1);
        String monthStart = sdf.format(c.getTime());
        c.set(Calendar.DAY_OF_MONTH, day);
        String dayStart = sdf.format(c.getTime());
        c.add(Calendar.DAY_OF_MONTH, 1);
        String end = sdf.format(c.getTime());
        //订单
        List<BaseOrder> orderListDay = baseOrderService.list(new QueryWrapper<BaseOrder>()
                .eq("store_id", storeId)
                .eq("order_status", "1")
                .ge("date_format(create_time, '%Y-%m-%d')", dayStart)
                .lt("date_format(create_time, '%Y-%m-%d')", end));
        List<BaseOrder> orderListMonth = baseOrderService.list(new QueryWrapper<BaseOrder>()
                .eq("store_id", storeId)
                .eq("order_status", "1")
                .ge("date_format(create_time, '%Y-%m-%d')", monthStart)
                .lt("date_format(create_time, '%Y-%m-%d')", end));
        int orderCountDay = orderListDay.size();
        int orderCountMonth = orderListMonth.size();
        //销售额 ，营业额
        BigDecimal orderSaleDay = orderListDay.stream().map(o -> o.getRealAmount() == null ? BigDecimal.ZERO : new BigDecimal(String.valueOf(o.getRealAmount()))).reduce(BigDecimal::add).orElse(BigDecimal.ZERO);
        BigDecimal orderSaleMonth = orderListMonth.stream().map(o -> o.getRealAmount() == null ? BigDecimal.ZERO : new BigDecimal(String.valueOf(o.getRealAmount()))).reduce(BigDecimal::add).orElse(BigDecimal.ZERO);
//股东分红 ?
        BigDecimal stockDividendDay = orderListDay.stream().map(o -> o.getStockPercentage() == null ? BigDecimal.ZERO : new BigDecimal(String.valueOf(o.getStockPercentage()))).reduce(BigDecimal::add).orElse(BigDecimal.ZERO);
        BigDecimal stockDividendMonth = orderListMonth.stream().map(o -> o.getStockPercentage() == null ? BigDecimal.ZERO : new BigDecimal(String.valueOf(o.getStockPercentage()))).reduce(BigDecimal::add).orElse(BigDecimal.ZERO);
        //
        BigDecimal staffSaleCommissionDay = orderListDay.stream().map(o -> o.getStaffPercentage() == null ? BigDecimal.ZERO : new BigDecimal(String.valueOf(o.getStaffPercentage()))).reduce(BigDecimal::add).orElse(BigDecimal.ZERO);
        BigDecimal staffSaleCommissionMonth = orderListMonth.stream().map(o -> o.getStaffPercentage() == null ? BigDecimal.ZERO : new BigDecimal(String.valueOf(o.getStaffPercentage()))).reduce(BigDecimal::add).orElse(BigDecimal.ZERO);
        //带动营业额
        BigDecimal driveTurnoverDay = orderListDay.stream().map(o -> o.getDriveTurnoverAll() == null ? BigDecimal.ZERO : new BigDecimal(String.valueOf(o.getDriveTurnoverAll()))).reduce(BigDecimal::add).orElse(BigDecimal.ZERO);
        BigDecimal driveTurnoverMonth = orderListMonth.stream().map(o -> o.getDriveTurnoverAll() == null ? BigDecimal.ZERO : new BigDecimal(String.valueOf(o.getDriveTurnoverAll()))).reduce(BigDecimal::add).orElse(BigDecimal.ZERO);
        //
        BigDecimal stewardDividendDay = orderListDay.stream().map(o -> o.getStaffShareMoney() == null ? BigDecimal.ZERO : new BigDecimal(String.valueOf(o.getStaffShareMoney()))).reduce(BigDecimal::add).orElse(BigDecimal.ZERO);
        BigDecimal stewardDividendMonth = orderListMonth.stream().map(o -> o.getStaffShareMoney() == null ? BigDecimal.ZERO : new BigDecimal(String.valueOf(o.getStaffShareMoney()))).reduce(BigDecimal::add).orElse(BigDecimal.ZERO);

        //订单核销
        List<BaseOrderServiceWriteoff> boswListDay = baseOrderServiceWriteoffService.list(new QueryWrapper<BaseOrderServiceWriteoff>()
                .eq("store_id", storeId)
                .ge("date_format(writeoff_time, '%Y-%m-%d')", dayStart)
                .lt("date_format(writeoff_time, '%Y-%m-%d')", end));
        List<BaseOrderServiceWriteoff> boswListMonth = baseOrderServiceWriteoffService.list(new QueryWrapper<BaseOrderServiceWriteoff>()
                .eq("store_id", storeId)
                .ge("date_format(writeoff_time, '%Y-%m-%d')", monthStart)
                .lt("date_format(writeoff_time, '%Y-%m-%d')", end));
        //
        BigDecimal staffServeCommissionDay = boswListDay.stream().map(o -> o.getServiceCommission() == null ? BigDecimal.ZERO : new BigDecimal(String.valueOf(o.getServiceCommission()))).reduce(BigDecimal::add).orElse(BigDecimal.ZERO);
        BigDecimal staffServeCommissionMonth = boswListMonth.stream().map(o -> o.getServiceCommission() == null ? BigDecimal.ZERO : new BigDecimal(String.valueOf(o.getServiceCommission()))).reduce(BigDecimal::add).orElse(BigDecimal.ZERO);

        List<MemberManagement> memberListDay = memberManagementService.list(new QueryWrapper<MemberManagement>()
                .eq("store_id", storeId)
                .eq("userinfo_status", "1")
                .eq("member_type", "店铺会员")
                .ge("date_format(create_time, '%Y-%m-%d')", dayStart)
                .lt("date_format(create_time, '%Y-%m-%d')", end));
        List<MemberManagement> memberListMonth = memberManagementService.list(new QueryWrapper<MemberManagement>()
                .eq("store_id", storeId)
                .eq("userinfo_status", "1")
                .eq("member_type", "店铺会员")
                .ge("date_format(create_time, '%Y-%m-%d')", monthStart)
                .lt("date_format(create_time, '%Y-%m-%d')", end));
        int memberCountDay = memberListDay.size();
        int memberCountMonth = memberListMonth.size();
        //股东数
        List<MemberManagement> stockMemberListDay = memberManagementService.list(new QueryWrapper<MemberManagement>()
                .eq("store_id", storeId)
                .eq("userinfo_status", "1")
                .eq("member_type", "股东会员")
                .ge("date_format(create_time, '%Y-%m-%d')", dayStart)
                .lt("date_format(create_time, '%Y-%m-%d')", end));
        List<MemberManagement> stockMemberListMonth = memberManagementService.list(new QueryWrapper<MemberManagement>()
                .eq("store_id", storeId)
                .eq("userinfo_status", "1")
                .eq("member_type", "股东会员")
                .ge("date_format(create_time, '%Y-%m-%d')", monthStart)
                .lt("date_format(create_time, '%Y-%m-%d')", end));
        int stockMemberCountDay = stockMemberListDay.size();
        int stockMemberCountMonth = stockMemberListMonth.size();
        //
        List<StockManage> stockListDay = stockManageService.list(new QueryWrapper<StockManage>()
                .eq("store_id", storeId)
                .ge("date_format(create_time, '%Y-%m-%d')", dayStart)
                .lt("date_format(create_time, '%Y-%m-%d')", end));
        List<StockManage> stockListMonth = stockManageService.list(new QueryWrapper<StockManage>()
                .eq("store_id", storeId)
                .ge("date_format(create_time, '%Y-%m-%d')", monthStart)
                .lt("date_format(create_time, '%Y-%m-%d')", end));
        int stockCountDay = stockListDay.size();
        int stockCountMonth = stockListMonth.size();

        Map<String, Object> result = new HashMapEx<>();
        result.put("orderCountDay", orderCountDay);

        result.put("orderCountMonth", orderCountMonth);
        result.put("orderSaleDay", orderSaleDay);
        result.put("orderSaleMonth", orderSaleMonth);
        //次卡消耗

        List<BaseOrderWriteoffRecord> timeCardsList = baseOrderWriteoffRecordService.list(new QueryWrapper<BaseOrderWriteoffRecord>()
                .eq("store_id", storeId)
                .ge("date_format(create_time, '%Y-%m-%d')", dayStart)
                .lt("date_format(create_time, '%Y-%m-%d')", end));

        Double timesCardDay = getSum(timeCardsList);

        List<BaseOrderWriteoffRecord> timeCardsMonthList = baseOrderWriteoffRecordService.list(new QueryWrapper<BaseOrderWriteoffRecord>()
                .eq("store_id", storeId)
                .ge("date_format(create_time, '%Y-%m-%d')", monthStart)
                .lt("date_format(create_time, '%Y-%m-%d')", end));
        Double timesCardMonth = getSum(timeCardsMonthList);

        result.put("timesCardDay", timesCardDay);
        result.put("timesCardMonth", timesCardMonth);
        // 员工销售提成 base_order

        // 贵宾卡
        List<VipOrderRecord> orderRecords4day = vipOrderRecordService.list(new QueryWrapper<VipOrderRecord>().eq("store_id", storeId)
                .ge("date_format(create_time, '%Y-%m-%d')", dayStart)
                .lt("date_format(create_time, '%Y-%m-%d')", end));
        Double VipCardAmount4Day = getSum4VipCard(orderRecords4day);
        List<VipOrderRecord> orderRecords4month = vipOrderRecordService.list(new QueryWrapper<VipOrderRecord>().eq("store_id", storeId)
                .ge("date_format(create_time, '%Y-%m-%d')", monthStart)
                .lt("date_format(create_time, '%Y-%m-%d')", end));
        Double VipCardAmount4Month = getSum4VipCard(orderRecords4month);

        Double totalTurnoverDay = orderSaleDay.doubleValue() + VipCardAmount4Day + timesCardDay;
        Double totalTurnoverMonth = orderSaleMonth.doubleValue() + VipCardAmount4Month + timesCardMonth;
        //LukasLi 营业额 商品 次卡 + 充值和贵宾卡(新增的)
        result.put("totalTurnoverDay", ToolsUtils.formatNumber(totalTurnoverDay));
        result.put("totalTurnoverMonth", ToolsUtils.formatNumber(totalTurnoverMonth));

        //TODO 余额消耗 (会员贵宾卡余额+股东余额)
        List<Map<String, Object>> banlanceList = homePageService.listBalanceCount(storeId, "X", dayStart, end);
        Double balanceAmountDay = getMapValueSum(banlanceList);
        List<Map<String, Object>> banlanceMonthList = homePageService.listBalanceCount(storeId, "X", monthStart, end);
        Double balanceAmountMonth = getMapValueSum(banlanceMonthList);

        result.put("balanceAmountDay", balanceAmountDay);
        result.put("balanceAmountMonth", balanceAmountMonth);

        result.put("staffSaleCommissionDay", staffSaleCommissionDay);
        result.put("staffSaleCommissionMonth", staffSaleCommissionMonth);
        // 员工服务提成 base_order_service_writeoff 核销
        result.put("staffServeCommissionDay", staffServeCommissionDay);
        result.put("staffServeCommissionMonth", staffServeCommissionMonth);
        // 带动营业额 base_order
        result.put("driveTurnoverDay", driveTurnoverDay);
        result.put("driveTurnoverMonth", driveTurnoverMonth);
        // 股东分红 base_order
        result.put("stockDividendDay", stockDividendDay);
        result.put("stockDividendMonth", stockDividendMonth);
        // 股东管家分红 base_order
        result.put("stewardDividendDay", stewardDividendDay);
        result.put("stewardDividendMonth", stewardDividendMonth);
        //应该是店铺会员
        result.put("memberCountDay", memberCountDay);
        result.put("memberCountMonth", memberCountMonth);
        //股东会员
        result.put("stockMemberCountDay", stockMemberCountDay);
        result.put("stockMemberCountMonth", stockMemberCountMonth);
        //总会数 = 股东会员 + 店铺会员
        result.put("totalMemberCountDay", stockMemberCountDay + memberCountDay);
        result.put("totalMemberCountMonth", stockMemberCountMonth + memberCountMonth);

        //股东数
        result.put("stockCountDay", stockCountDay);
        result.put("stockCountMonth", stockCountMonth);


        return Result.OK(((HashMapEx<String, Object>) result).getMap());
    }

    private Double getSum4VipCard(List<VipOrderRecord> vipOrderRecords) {
        Double result = 0.0;
        for (VipOrderRecord r : vipOrderRecords) {
            result = result + r.getSellingPrice();
        }
        return result;
    }

    private Double getSum(List<BaseOrderWriteoffRecord> timeCardsList) {
        Double result = 0.0;
        for (BaseOrderWriteoffRecord r : timeCardsList) {
            String orderProjectId = r.getOrderProjectId();
            BaseOrderProject orderProject = baseOrderProjectService.getById(orderProjectId);
            if (orderProject != null) {
                String projectId = orderProject.getProjectId();
                String unitPrice = orderProject.getUnitPrice();
                List<BaseJobServeItem> list = baseJobServeItemService.list(new QueryWrapper<BaseJobServeItem>().eq("project_id", projectId));
                if (list.size() == 1) {
                    Integer serveNum = list.get(0).getServeNum();
                    BigDecimal bigDecimal = new BigDecimal(unitPrice);
                    result = result + bigDecimal.divide(BigDecimal.valueOf(serveNum),2,BigDecimal.ROUND_HALF_UP).doubleValue();
                }
            }
        }
        return result;
    }

    /**
     * 首页-累计数据
     */
    @PostMapping("/data2")
    public Result<?> data2(HttpServletRequest req) {

        String token = TokenUtils.getTokenByRequest(req);
        String storeId = (String) redisUtils.get(RedisUtils.storeId + token);
        if (oConvertUtils.isEmpty(storeId)) {
            return Result.error("请先到首页选择店铺");
        }
        if (storeId.contains("过期")) {
            return Result.error("店铺已过期，续费后才可操作");
        }

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String end = sdf.format(new Date());

        int waitPayOrderCount = baseOrderService.count(new QueryWrapper<BaseOrder>()
                .eq("store_id", storeId)
                .eq("order_status", "0"));

        int onSaleCommodityCount = commodityManagementService.count(new QueryWrapper<CommodityManagement>()
                .eq("store_id", storeId)
                .eq("status", "1"));

        int zeroInventoryCommodityCount = commodityManagementService.count(new QueryWrapper<CommodityManagement>()
                .eq("store_id", storeId)
                .eq("inventory", 0));

        Map<String, Object> result = new HashMap<>();
        result.put("waitPayOrderCount", waitPayOrderCount);
        result.put("onSaleCommodityCount", onSaleCommodityCount);
        result.put("zeroInventoryCommodityCount", zeroInventoryCommodityCount);
        // TODO 提现待审核
        result.put("withdrawAuditCount", 0);
        return Result.OK(result);
    }

    /**
     * 首页-近7天营业额走势
     */
    @PostMapping("/chart1")
    public Result<?> chart1(HttpServletRequest req) {

        String token = TokenUtils.getTokenByRequest(req);
        String storeId = (String) redisUtils.get(RedisUtils.storeId + token);
        if (oConvertUtils.isEmpty(storeId)) {
            return Result.error("请先到首页选择店铺");
        }
        if (storeId.contains("过期")) {
            return Result.error("店铺已过期，续费后才可操作");
        }

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Calendar c = Calendar.getInstance();
        c.setTime(new Date());
        String end = sdf.format(c.getTime());
        c.add(Calendar.DAY_OF_MONTH, -6);
        String start = sdf.format(c.getTime());

        List<Map<String, Object>> orderSaleList = homePageService.listOrderSale(storeId, start, end);

        List<String> timeList = new ArrayList<>();
        List<Double> dataList = new ArrayList<>();
        for (int i = 0; i < 7; i++) {
            String time = sdf.format(c.getTime());
            timeList.add(time);
            c.add(Calendar.DAY_OF_MONTH, 1);
            Map<String, Object> map = orderSaleList.stream().filter(m -> time.equals(String.valueOf(m.get("time")))).findFirst().orElse(null);
            if (map == null) {
                dataList.add(0.00);
            } else {
                dataList.add(Double.parseDouble(String.valueOf(map.get("realAmount"))));
            }
        }

        Map<String, Object> result = new HashMap<>();
        result.put("data", dataList);
        result.put("dataX", timeList);
        return Result.OK(result);
    }

    /**
     * 首页-近7天客流量走势
     */
    @PostMapping("/chart2")
    public Result<?> chart2(HttpServletRequest req) {

        String token = TokenUtils.getTokenByRequest(req);
        String storeId = (String) redisUtils.get(RedisUtils.storeId + token);
        if (oConvertUtils.isEmpty(storeId)) {
            return Result.error("请先到首页选择店铺");
        }
        if (storeId.contains("过期")) {
            return Result.error("店铺已过期，续费后才可操作");
        }

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Calendar c = Calendar.getInstance();
        c.setTime(new Date());
        String end = sdf.format(c.getTime());
        c.add(Calendar.DAY_OF_MONTH, -6);
        String start = sdf.format(c.getTime());

        List<Map<String, Object>> orderCountList = homePageService.listOrderCount(storeId, start, end);

        List<String> timeList = new ArrayList<>();
        List<Integer> dataList = new ArrayList<>();
        for (int i = 0; i < 7; i++) {
            String time = sdf.format(c.getTime());
            timeList.add(time);
            c.add(Calendar.DAY_OF_MONTH, 1);
            Map<String, Object> map = orderCountList.stream().filter(m -> time.equals(String.valueOf(m.get("time")))).findFirst().orElse(null);
            if (map == null) {
                dataList.add(0);
            } else {
                dataList.add(Integer.parseInt(String.valueOf(map.get("count"))));
            }
        }

        Map<String, Object> result = new HashMap<>();
        result.put("data", dataList);
        result.put("dataX", timeList);
        return Result.OK(result);
    }

    /**
     * 数据-顶部数据
     */
    @PostMapping("/data3")
    public Result<?> data3(@RequestBody Map<String, Object> map, HttpServletRequest req) {

        String token = TokenUtils.getTokenByRequest(req);
        String storeId = (String) redisUtils.get(RedisUtils.storeId + token);
        if (oConvertUtils.isEmpty(storeId)) {
            return Result.error("请先到首页选择店铺");
        }
        if (storeId.contains("过期")) {
            return Result.error("店铺已过期，续费后才可操作");
        }

        String beginTime = map.get("beginTime") == null ? null : String.valueOf(map.get("beginTime"));
        String endTime = map.get("endTime") == null ? null : String.valueOf(map.get("endTime"));
        if (StringUtils.isEmpty(beginTime) || StringUtils.isEmpty(endTime)) {
            return Result.error("参数不全");
        }

        List<BaseOrder> orderList = baseOrderService.list(new QueryWrapper<BaseOrder>()
                .eq("store_id", storeId)
                .eq("order_status", "1")
                .ge("date_format(create_time, '%Y-%m-%d')", beginTime)
                .le("date_format(create_time, '%Y-%m-%d')", endTime));
        int orderCount = orderList.size();
        BigDecimal orderSale = orderList.stream().map(o -> o.getRealAmount() == null ? BigDecimal.ZERO : new BigDecimal(String.valueOf(o.getRealAmount()))).reduce(BigDecimal::add).orElse(BigDecimal.ZERO);
        BigDecimal stockDividend = orderList.stream().map(o -> o.getStockPercentage() == null ? BigDecimal.ZERO : new BigDecimal(String.valueOf(o.getStockPercentage()))).reduce(BigDecimal::add).orElse(BigDecimal.ZERO);
        BigDecimal staffSaleCommission = orderList.stream().map(o -> o.getStaffPercentage() == null ? BigDecimal.ZERO : new BigDecimal(String.valueOf(o.getStaffPercentage()))).reduce(BigDecimal::add).orElse(BigDecimal.ZERO);
        BigDecimal driveTurnover = orderList.stream().map(o -> o.getDriveTurnoverAll() == null ? BigDecimal.ZERO : new BigDecimal(String.valueOf(o.getDriveTurnoverAll()))).reduce(BigDecimal::add).orElse(BigDecimal.ZERO);
        BigDecimal stewardDividend = orderList.stream().map(o -> o.getStaffShareMoney() == null ? BigDecimal.ZERO : new BigDecimal(String.valueOf(o.getStaffShareMoney()))).reduce(BigDecimal::add).orElse(BigDecimal.ZERO);

        List<BaseOrderServiceWriteoff> boswList = baseOrderServiceWriteoffService.list(new QueryWrapper<BaseOrderServiceWriteoff>()
                .eq("store_id", storeId)
                .ge("date_format(writeoff_time, '%Y-%m-%d')", beginTime)
                .le("date_format(writeoff_time, '%Y-%m-%d')", endTime));
        BigDecimal staffServeCommission = boswList.stream().map(o -> o.getServiceCommission() == null ? BigDecimal.ZERO : new BigDecimal(String.valueOf(o.getServiceCommission()))).reduce(BigDecimal::add).orElse(BigDecimal.ZERO);

        List<MemberManagement> memberList = memberManagementService.list(new QueryWrapper<MemberManagement>()
                .eq("store_id", storeId)
                .ge("date_format(create_time, '%Y-%m-%d')", beginTime)
                .le("date_format(create_time, '%Y-%m-%d')", endTime));
        int memberCount = memberList.size();

        List<MemberManagement> stockMemberList = memberManagementService.list(new QueryWrapper<MemberManagement>()
                .eq("store_id", storeId)
                .eq("userinfo_status", "1")
                .eq("member_type", "股东会员")
                .ge("date_format(create_time, '%Y-%m-%d')", beginTime)
                .le("date_format(create_time, '%Y-%m-%d')", endTime));
        int stockMemberCount = stockMemberList.size();

        List<StockManage> stockList = stockManageService.list(new QueryWrapper<StockManage>()
                .eq("store_id", storeId)
                .ge("date_format(create_time, '%Y-%m-%d')", beginTime)
                .le("date_format(create_time, '%Y-%m-%d')", endTime));
        int stockCount = stockList.size();

        Map<String, Object> result = new HashMap<>();
        result.put("orderCount", orderCount);
        result.put("orderSale", orderSale);
        result.put("staffSaleCommission", staffSaleCommission);
        result.put("staffServeCommission", staffServeCommission);
        result.put("driveTurnover", driveTurnover);
        result.put("stockDividend", stockDividend);
        result.put("stewardDividend", stewardDividend);
        result.put("memberCount", memberCount);
        result.put("stockMemberCount", stockMemberCount);
        result.put("stockCount", stockCount);
        return Result.OK(result);
    }

    /**
     * 数据-订单数量折线图
     */
    @PostMapping("/chart3")
    public Result<?> chart3(@RequestBody Map<String, Object> map, HttpServletRequest req) {

        String token = TokenUtils.getTokenByRequest(req);
        String storeId = (String) redisUtils.get(RedisUtils.storeId + token);
        if (oConvertUtils.isEmpty(storeId)) {
            return Result.error("请先到首页选择店铺");
        }
        if (storeId.contains("过期")) {
            return Result.error("店铺已过期，续费后才可操作");
        }

        String beginTime = map.get("beginTime") == null ? null : String.valueOf(map.get("beginTime"));
        String endTime = map.get("endTime") == null ? null : String.valueOf(map.get("endTime"));
        if (StringUtils.isEmpty(beginTime) || StringUtils.isEmpty(endTime)) {
            return Result.error("参数不全");
        }

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Calendar c = Calendar.getInstance();
        try {
            Date beginDate = sdf.parse(beginTime);
            Date endDate = sdf.parse(endTime);
            if (beginDate.after(endDate)) {
                return Result.error("endTime应晚于beginTime");
            }
            c.setTime(beginDate);
        } catch (ParseException e) {
            log.error("[beginTime = {}]时间转换错误", beginTime, e);
            return Result.error("时间格式错误");
        }

        List<Map<String, Object>> orderCountList = homePageService.listOrderCount(storeId, beginTime, endTime);

        List<String> timeList = new ArrayList<>();
        List<Integer> dataList = new ArrayList<>();
        for (int i = 0; i < 365; i++) {
            String time = sdf.format(c.getTime());
            timeList.add(time);
            c.add(Calendar.DAY_OF_MONTH, 1);
            Map<String, Object> map1 = orderCountList.stream().filter(m -> time.equals(String.valueOf(m.get("time")))).findFirst().orElse(null);
            if (map1 == null) {
                dataList.add(0);
            } else {
                dataList.add(Integer.parseInt(String.valueOf(map1.get("count"))));
            }
            if (endTime.equals(time)) {
                break;
            }
        }

        Map<String, Object> result = new HashMap<>();
        result.put("data", dataList);
        result.put("dataX", timeList);
        return Result.OK(result);
    }

    /**
     * 数据-店铺会员/股东会员/股东数折线图
     */
    @PostMapping("/chart4")
    public Result<?> chart4(@RequestBody Map<String, Object> map, HttpServletRequest req) {

        String token = TokenUtils.getTokenByRequest(req);
        String storeId = (String) redisUtils.get(RedisUtils.storeId + token);
        if (oConvertUtils.isEmpty(storeId)) {
            return Result.error("请先到首页选择店铺");
        }
        if (storeId.contains("过期")) {
            return Result.error("店铺已过期，续费后才可操作");
        }

        String beginTime = map.get("beginTime") == null ? null : String.valueOf(map.get("beginTime"));
        String endTime = map.get("endTime") == null ? null : String.valueOf(map.get("endTime"));
        if (StringUtils.isEmpty(beginTime) || StringUtils.isEmpty(endTime)) {
            return Result.error("参数不全");
        }

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Calendar c = Calendar.getInstance();
        try {
            Date beginDate = sdf.parse(beginTime);
            Date endDate = sdf.parse(endTime);
            if (beginDate.after(endDate)) {
                return Result.error("endTime应晚于beginTime");
            }
            c.setTime(beginDate);
        } catch (ParseException e) {
            log.error("[beginTime = {}]时间转换错误", beginTime, e);
            return Result.error("时间格式错误");
        }

        List<Map<String, Object>> memberCountList = homePageService.listMemberCount(storeId, beginTime, endTime);
        List<Map<String, Object>> stockMemberCountList = homePageService.listStockMemberCount(storeId, beginTime, endTime);
        List<Map<String, Object>> stockCountList = homePageService.listStockCount(storeId, beginTime, endTime);

        List<String> timeList = new ArrayList<>();
        List<Integer> memberList = new ArrayList<>();
        List<Integer> stockMemberList = new ArrayList<>();
        List<Integer> stockList = new ArrayList<>();
        for (int i = 0; i < 365; i++) {
            String time = sdf.format(c.getTime());
            timeList.add(time);
            c.add(Calendar.DAY_OF_MONTH, 1);
            Map<String, Object> map1 = memberCountList.stream().filter(m -> time.equals(String.valueOf(m.get("time")))).findFirst().orElse(null);
            if (map1 == null) {
                memberList.add(0);
            } else {
                memberList.add(Integer.parseInt(String.valueOf(map1.get("count"))));
            }
            Map<String, Object> map2 = stockMemberCountList.stream().filter(m -> time.equals(String.valueOf(m.get("time")))).findFirst().orElse(null);
            if (map2 == null) {
                stockMemberList.add(0);
            } else {
                stockMemberList.add(Integer.parseInt(String.valueOf(map2.get("count"))));
            }
            Map<String, Object> map3 = stockCountList.stream().filter(m -> time.equals(String.valueOf(m.get("time")))).findFirst().orElse(null);
            if (map3 == null) {
                stockList.add(0);
            } else {
                stockList.add(Integer.parseInt(String.valueOf(map3.get("count"))));
            }
            if (endTime.equals(time)) {
                break;
            }
        }

        Map<String, Object> result = new HashMap<>();
        result.put("member", memberList);
        result.put("stockMember", stockMemberList);
        result.put("stock", stockList);
        result.put("dataX", timeList);
        return Result.OK(result);
    }

    /**
     * 数据-营业额/带动营业额/员工销售提成/员工服务提成/股东分红/股东管家分红折线图
     */
    @PostMapping("/chart5")
    public Result<?> chart5(@RequestBody Map<String, Object> map, HttpServletRequest req) {

        String token = TokenUtils.getTokenByRequest(req);
        String storeId = (String) redisUtils.get(RedisUtils.storeId + token);
        if (oConvertUtils.isEmpty(storeId)) {
            return Result.error("请先到首页选择店铺");
        }
        if (storeId.contains("过期")) {
            return Result.error("店铺已过期，续费后才可操作");
        }

        String beginTime = map.get("beginTime") == null ? null : String.valueOf(map.get("beginTime"));
        String endTime = map.get("endTime") == null ? null : String.valueOf(map.get("endTime"));
        if (StringUtils.isEmpty(beginTime) || StringUtils.isEmpty(endTime)) {
            return Result.error("参数不全");
        }

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Calendar c = Calendar.getInstance();
        try {
            Date beginDate = sdf.parse(beginTime);
            Date endDate = sdf.parse(endTime);
            if (beginDate.after(endDate)) {
                return Result.error("endTime应晚于beginTime");
            }
            c.setTime(beginDate);
        } catch (ParseException e) {
            log.error("[beginTime = {}]时间转换错误", beginTime, e);
            return Result.error("时间格式错误");
        }

        List<Map<String, Object>> orderSaleList = homePageService.listOrderSale(storeId, beginTime, endTime);
        List<Map<String, Object>> serveCommissionList = homePageService.listServeCommission(storeId, beginTime, endTime);

        List<String> timeList = new ArrayList<>();
        List<Double> orderSaleList1 = new ArrayList<>();
        List<Double> driveTurnoverList = new ArrayList<>();
        List<Double> staffSaleCommissionList = new ArrayList<>();
        List<Double> staffServeCommissionList = new ArrayList<>();
        List<Double> stockDividendList = new ArrayList<>();
        List<Double> stewardDividendList = new ArrayList<>();
        for (int i = 0; i < 365; i++) {
            String time = sdf.format(c.getTime());
            timeList.add(time);
            c.add(Calendar.DAY_OF_MONTH, 1);
            Map<String, Object> map1 = orderSaleList.stream().filter(m -> time.equals(String.valueOf(m.get("time")))).findFirst().orElse(null);
            if (map1 == null) {
                orderSaleList1.add(0.00);
                driveTurnoverList.add(0.00);
                staffSaleCommissionList.add(0.00);
                stockDividendList.add(0.00);
                stewardDividendList.add(0.00);
            } else {
                orderSaleList1.add(Double.parseDouble(String.valueOf(map1.get("realAmount"))));
                driveTurnoverList.add(Double.parseDouble(String.valueOf(map1.get("driveTurnover"))));
                staffSaleCommissionList.add(Double.parseDouble(String.valueOf(map1.get("staffSaleCommission"))));
                stockDividendList.add(Double.parseDouble(String.valueOf(map1.get("stockDividend"))));
                stewardDividendList.add(Double.parseDouble(String.valueOf(map1.get("stewardDividend"))));
            }
            Map<String, Object> map2 = serveCommissionList.stream().filter(m -> time.equals(String.valueOf(m.get("time")))).findFirst().orElse(null);
            if (map2 == null) {
                staffServeCommissionList.add(0.00);
            } else {
                staffServeCommissionList.add(Double.parseDouble(String.valueOf(map2.get("staffServeCommission"))));
            }
            if (endTime.equals(time)) {
                break;
            }
        }

        Map<String, Object> result = new HashMap<>();
        result.put("orderSale", orderSaleList1);
        result.put("driveTurnover", driveTurnoverList);
        result.put("staffSaleCommission", staffSaleCommissionList);
        result.put("staffServeCommission", staffServeCommissionList);
        result.put("stockDividend", stockDividendList);
        result.put("stewardDividend", stewardDividendList);
        result.put("dataX", timeList);
        return Result.OK(result);
    }

    /**
     * 首页-本月数据
     */
    @PostMapping("/data5")
    public Result<?> data5(HttpServletRequest req) {
        return Result.OK();
        /*
        营业额
新增
余额消耗
消次卡耗
         */
    }
}
